adminPanel.controller('ExtraAcademicsEditableGrid',['$scope', '$filter', '$http', '$q','cacheFactory',function($scope, $filter, $http, $q, cacheFactory) {
	$q;
	$scope.gradeList = cacheFactory.getGradeList();
	$scope.certificationList = cacheFactory.getCertificationList();
	$scope.showGrid=false;
	$scope.searchCriteria.recordType='EXTRA_ACADEMICS';
	$scope.searchCriteria.termId=null;//this is must for non term items
	//use to send data to server
	var studentRecord={"extraAcademics":null, "searchCriteria":null};
	
	//get the subjects loaded into system
	$scope.extraAcademicsVos =[];
	
	$scope.getDetails= function(){                 
		studentRecord.searchCriteria= $scope.searchCriteria;
		$http.post(BASE_URL+"admin/handleRequest/studentRecord/GET_EXTRA_ACADEMICS_BY_GRADE/",studentRecord).success(function(data){
			if(data.status=='SUCCESS'){
				$scope.extraAcademicsVos=data.result;	
				$scope.showGrid=true;
			}
			else if(data.status=='NOT_FOUND'){
				$scope.extraAcademicsVos =[];
				alert("No record found for this entity");
				$scope.showGrid=true;
			}
			else{
				alert(data.status +":"+data.msg);
				$scope.showGrid=true;
			}
			$scope.getRecommendations();
		}).error(function(){
			ERROR_LOGGER("Server Error");
		});
	}
	
	$scope.recommendations=[];
	$scope.showRecommendation=false;
	$scope.handleSavedRecommendation=function(data){
		if(data.type=='SAVE_RECOMMENDATION'){
			$scope.getRecommendations();
		}
	}
	$scope.handleDeletedRecommendation=function(data){
		if(data.type=='DELETE_RECOMMENDATION'){
			$scope.getRecommendations();
		}
	}
	
	
	$scope.getRecommendations=function(){
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/RECOMMENDATION_GET', {searchCriteria:$scope.searchCriteria});
	    httpResult.success(function(data){
	    	if(data.status=='SUCCESS'){
	    		$scope.recommendations=data.result;
	    		$scope.showRecommendation=true;
	    	}else{
	    		$scope.showRecommendation=false;
	    	}
	    });
	}
	//register event
	  RegisterEventHandler("ExtraAcademicsEditableGrid1",$scope.handleDeletedRecommendation);
	  RegisterEventHandler("ExtraAcademicsEditableGrid2",$scope.handleSavedRecommendation);
	
	
	$scope.showCertificates = function(extraAcademicsVo) {
	    var selected = [];
	    if(extraAcademicsVo.certificationId) {
	      selected = $filter('filter')($scope.certificationList, {id: extraAcademicsVo.certificationId});
	    }
	    return selected.length ? selected[0].certificationName : 'Not set';
	};
	
	
	$scope.criteriaChanged=function(){
		$scope.showGrid=false;
		$scope.extraAcademicsVos=[];
		$scope.recommendations ="";
		$scope.recommendationId ="";
	}

	  $scope.checkValue = function(data, id) {
		  //validation will go here
	  };

	  // filter extraAcademicsVo to show
	  $scope.filterExtraAcademics = function(extraAcademicsRow) {
	    return extraAcademicsRow.rowDeleted !== true;
	  };

	  // mark user as deleted
	  $scope.deleteExtraAcademicsRow = function(cid,sid) {
		 
		  var filtered = $filter('filter')($scope.extraAcademicsVos, {sid: sid});
	    
	    if (filtered.length) {
	      filtered[0].rowDeleted = true;
	      $scope.extraAcademicsVos[sid].rowDeleted=true;
	    }
	  };
	  
	  
	  $scope.handleAttachImage=function(data,extraAcademicVo){
			if(data.status=='SUCCESS'){
				var attachedFileId=data.result[0].id;
				var rowId = extraAcademicVo.sid;
				$scope.extraAcademicsVos[rowId].certificateAttachmentId=attachedFileId;	
			}else{
				ERROR_LOGGER(data);
			}
			$('#myModal').modal('toggle');
		}
		
		//called after file attached by user.
		$scope.handleDeleteImage=function(data,extraAcademicVo){
			if(data.status=='SUCCESS'){
				$scope.extraAcademicsVos[extraAcademicVo.cid-1].certificateAttachmentId=0;	
			}else{
				ERROR_LOGGER(data);
			}
		}
	  
	  
	  // add Extra Academic Row
	  $scope.addExtraAcademicsRow = function() {
	    $scope.extraAcademicsVos.push({
	      cid: $scope.extraAcademicsVos.length+1,
	      sid: 0,
	      certificationId: null,
	      dated: new Date(),
	      gradeId: $scope.searchCriteria.gradeId,
	      schoolRank: null,
	      stateRank:null,
	      allIndiaRank: null,
	      remark:null,
	      certificateAttachmentId:null,
	      newRow:true
	    });
	  };

	  // cancel all changes
	  $scope.cancel = function() {
	    for (var i = $scope.extraAcademicsVos.length; i--;) {
	      var vo = $scope.extraAcademicsVos[i];    
	      // undelete
	      if (vo.rowDeleted) {
	    	  $scope.extraAcademicsVos[i].rowDeleted=false;
	         //delete vo.isDeleted;
	      }
	      // remove new 
	      if (vo.newRow) {
	        $scope.extraAcademicsVos.splice(i, 1);
	      }
	    };
	  };

	  // save edits
	  $scope.saveTable = function() {
	    var results = [];
	    for (var i = $scope.extraAcademicsVos.length; i--;) {
	      var vo = $scope.extraAcademicsVos[i];
	      // actually delete user
	      if (vo.rowDeleted) {
	        //$scope.extraAcademicsVo.splice(i, 1);
	      }
	      // mark as not new 
	      if (vo.newRow) {
	    	  vo.newRow = true;
	      }
	      vo.gradeId=$scope.searchCriteria.gradeId;
	    }
	    //Create student vo object
	    studentRecord.extraAcademics=$scope.extraAcademicsVos;
	    studentRecord.searchCriteria= $scope.searchCriteria;
	    // send on server
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/SAVE_EXTRA_ACADEMICS', studentRecord);
	    httpResult.success(function(data){
	    		if(data.status="SUCCESS"){
	    			$.each($scope.extraAcademicsVos,function(a,b){
		    			b.newRow=false;
		    		});
	    			alert("Record Saved Successfully");
	    		}
	    		//results.push(data.result)
	    		//ok so this is really important to save newRow=false after saving current grid
	    		
	    		
	    });
	    results.push(httpResult);
	    return $q.all(results);
	  };
	
	
}]);